package com.jy.appmarket.cards;

import it.gmariotti.cardslib.library.internal.CardHeader;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.jy.app.market.idata.card.CardGroupApkTop;
import com.jy.app.market.idata.data.Apk;
import com.jy.appmarket.AppMarketApplication;
import com.jy.appmarket.R;
import com.jy.appmarket.activity.AppDetailActivity;
import com.jy.appmarket.download.DownloadActivity;
import com.jy.appmarket.download.DownloadItem;
import com.jy.appmarket.download.DownloadService;
import com.jy.appmarket.download.DownloadUtils;
import com.jy.appmarket.statistics.ApkSource;
import com.jy.appmarket.utils.IdataUtils;
import com.jy.appmarket.utils.LoadImageUtils;
import com.jy.appmarket.utils.LogUtil;
import com.jy.appmarket.utils.PackageUtils;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 类说明：
 * 
 * @author Baker.li
 * @date 2015年8月21日
 * @version 1.0
 */

public class GroupApkTopUICard extends DownloadableUICard {
	private static final String TAG = "GroupApkTopUICard";
	private DownloadActivity mDLActivity;
	private CardHeader mHeader;
	private CardGroupApkTop mGroupApkTop;
	private int apkCount = 0;
	private AppHolder[] mHolders;
	private int mBlueTextColor;
	private int mOrangeTextColor;
	private int mGrayTextColor;

	public GroupApkTopUICard(Context context, CardGroupApkTop groupApkTop) {
		super(context, R.layout.group_apk_top_card);
		mDLActivity = (DownloadActivity) context;
		mGroupApkTop = groupApkTop;
		init();
	}

	private void init() {
		Resources r = getContext().getResources();
		mBlueTextColor = r.getColor(R.color.download_btn_blue_style_text);
		mOrangeTextColor = r.getColor(R.color.download_btn_orange_style_text);
		mGrayTextColor = r.getColor(R.color.download_btn_gray_style_text);

		mHeader = new GroupApkTopHeader(getContext(), mGroupApkTop);
		addCardHeader(mHeader);
		List<Apk> apks = mGroupApkTop.getApks();
		if (apks == null || apks.size() == 0) {
			return;
		}
		if (apks.size() >= 5) {
			apkCount = 5;
		} else {
			apkCount = apks.size();
		}
		mHolders = new AppHolder[apkCount];
		initApkHolder();
	}

	private void initApkHolder() {
		for (int i = 0; i < apkCount; i++) {
			mHolders[i] = new AppHolder();
			Apk apk = mGroupApkTop.getApks().get(i);
			String dlId = DownloadUtils.generateDownloadId(apk.getPackageName(), apk.getVersionCode());
			String icon = IdataUtils.getIconUrl(apk.getIcons());
			mHolders[i].iconUrl = icon;
			mHolders[i].apk = apk;
			mHolders[i].dlId = dlId;
			mHolders[i].downloadItem = mDLActivity.getDownloadById(dlId);
		}
	}

	@Override
	public int getType() {
		return 10;
	}

	@Override
	public void setupInnerViewElements(ViewGroup parent, View view) {

		View[] apkViews = new View[] { parent.findViewById(R.id.group_apk_top_apk1),
				parent.findViewById(R.id.group_apk_top_apk2), parent.findViewById(R.id.group_apk_top_apk3),
				parent.findViewById(R.id.group_apk_top_apk4), parent.findViewById(R.id.group_apk_top_apk5) };

		for (int i = 0; i < apkViews.length; i++) {
			apkViews[i].setVisibility(i < apkCount ? View.VISIBLE : View.GONE);
		}

		View[] dividers = new View[] { parent.findViewById(R.id.group_apk_top_divider1),
				parent.findViewById(R.id.group_apk_top_divider2), parent.findViewById(R.id.group_apk_top_divider3),
				parent.findViewById(R.id.group_apk_top_divider4) };
		for (int i = 0; i < dividers.length; i++) {
			dividers[i].setVisibility(i < apkCount - 1 ? View.VISIBLE : View.GONE);
		}

		for (int i = 0; i < apkCount; i++) {
			mHolders[i].top = i + 1;
			mHolders[i].topView = apkViews[i].findViewById(R.id.app_top_card_top);
			mHolders[i].button = apkViews[i].findViewById(R.id.app_top_card_download_button);
			mHolders[i].desc = apkViews[i].findViewById(R.id.app_top_card_desc);
			mHolders[i].icon = apkViews[i].findViewById(R.id.app_top_card_icon);
			mHolders[i].info = apkViews[i].findViewById(R.id.app_top_card_info);
			mHolders[i].name = apkViews[i].findViewById(R.id.app_top_card_name);
			mHolders[i].progress = apkViews[i].findViewById(R.id.app_top_card_progressbar);
			mHolders[i].progressStatus = apkViews[i].findViewById(R.id.app_top_card_statuswithprogress);

			mHolders[i].progressLayoutView = apkViews[i].findViewById(R.id.app_top_card_progress_layout);
			mHolders[i].progressSize = apkViews[i].findViewById(R.id.app_top_card_statuswithsize);

			mHolders[i].name.setText((AppMarketApplication.showLocal & mHolders[i].apk.getLocal() > 0 ? "★" : "")
					+ mHolders[i].apk.getTitle());
			String detailStr = mHolders[i].apk.getRecommend();
			if (TextUtils.isEmpty(detailStr)) {
				detailStr = mHolders[i].apk.getTagline();
				if (TextUtils.isEmpty(detailStr)) {
					detailStr = mHolders[i].apk.getDescription();
				}
			}
			mHolders[i].desc.setText(detailStr);
			ImageLoader.getInstance().displayImage(mHolders[i].iconUrl, mHolders[i].icon,
					LoadImageUtils.getListIconDisplayOption(mDLActivity));

			final int index = i;
			apkViews[i].setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					Apk apk = mHolders[index].apk;
					Intent detail = new Intent(mDLActivity, AppDetailActivity.class);
					detail.putExtra(AppDetailActivity.EXTRA_NAME, apk.getTitle());
					detail.putExtra(AppDetailActivity.EXTRA_PKG, apk.getPackageName());
					detail.putExtra(AppDetailActivity.EXTRA_SOURCE, ApkSource.toSourceString(getApkSource()));
					mDLActivity.startActivity(detail);
				}
			});
			setupApkView(mHolders[i]);
		}
	}

	private void setupApkView(final AppHolder h) {
		if (h.info == null) {
			return;
		}
		Apk apk = h.apk;
		if (h.button == null) {
			LogUtil.d(TAG, "view not inited");
			return;
		}

		switch (h.top) {
		case 1:
			// h.topView.setBackgroundResource(R.drawable.top_num_1_background);
			h.topView.setTextColor(0xfff53a05);
			break;
		case 2:
			// h.topView.setBackgroundResource(R.drawable.top_num_2_background);
			h.topView.setTextColor(0xfffa8a00);
			break;
		case 3:
			// h.topView.setBackgroundResource(R.drawable.top_num_3_background);
			h.topView.setTextColor(0xfff7c600);
			break;
		default:
			// h.topView.setBackgroundResource(R.drawable.top_num_others_background);
			h.topView.setTextColor(0xffb2b2b2);
			break;
		}
		h.topView.setText(String.valueOf(h.top));

		String infoText = apk.getInstalledCountStr() + "人安装  "
				+ Formatter.formatFileSize(getContext(), safeInt(apk.getBytes()));
		@SuppressWarnings("deprecation")
		Drawable drawableLeft = getContext().getResources().getDrawable(R.drawable.download_info);
		int status = mDLActivity.getDownloadStatus(h.dlId, apk.getPackageName(), apk.getVersionCode());

		switch (status) {
		case DownloadService.STATUS_CAN_INSTALL:
			h.info.setVisibility(View.VISIBLE);
			h.progressLayoutView.setVisibility(View.GONE);

			h.info.setText(R.string.wait_for_install);
			h.info.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
			h.button.setBackgroundResource(R.drawable.download_button_blue);
			h.button.setTextColor(mBlueTextColor);
			h.button.setText(R.string.install);
			h.button.setClickable(true);
			break;

		case DownloadService.STATUS_PAUSED_BY_ERROR:
			h.info.setVisibility(View.GONE);
			h.progressLayoutView.setVisibility(View.VISIBLE);

			h.progressStatus.setText(R.string.download_error);
			h.progressSize.setText(getProgressString(h.downloadItem, h.apk, h.dlId));
			h.progress.setIndeterminate(false);
			h.progress.setProgress(getProgress(h.downloadItem, h.apk, h.dlId));

			h.button.setTextColor(mOrangeTextColor);
			h.button.setBackgroundResource(R.drawable.download_button_orange);
			h.button.setText(R.string.retry);
			h.button.setClickable(true);

			break;
		case DownloadService.STATUS_INSTALLED:
			h.info.setVisibility(View.VISIBLE);
			h.progressLayoutView.setVisibility(View.GONE);

			h.info.setText(infoText);
			h.info.setCompoundDrawablesWithIntrinsicBounds(drawableLeft, null, null, null);
			h.button.setTextColor(mGrayTextColor);
			h.button.setBackgroundResource(R.drawable.download_button_gray);
			h.button.setText(R.string.open);
			h.button.setClickable(true);
			break;
		case DownloadService.STATUS_NO_STATUS:
			h.info.setVisibility(View.VISIBLE);
			h.progressLayoutView.setVisibility(View.GONE);

			h.info.setText(infoText);
			h.info.setCompoundDrawablesWithIntrinsicBounds(drawableLeft, null, null, null);
			h.button.setTextColor(mBlueTextColor);
			h.button.setBackgroundResource(R.drawable.download_button_blue);
			h.button.setText(R.string.download);
			h.button.setClickable(true);
			break;
		case DownloadService.STATUS_PAUSED_BY_MOBILE_NETWORK:
			h.info.setVisibility(View.GONE);
			h.progressLayoutView.setVisibility(View.VISIBLE);

			h.progressStatus.setText(R.string.wait_for_wifi);
			h.progressSize.setText(getProgressString(h.downloadItem, h.apk, h.dlId));
			h.progress.setIndeterminate(false);
			h.progress.setProgress(getProgress(h.downloadItem, h.apk, h.dlId));

			h.button.setTextColor(mBlueTextColor);
			h.button.setBackgroundResource(R.drawable.download_button_blue);
			h.button.setText(R.string.go_on);
			h.button.setClickable(true);

			break;
		case DownloadService.STATUS_PAUSED_BY_USER:
			h.info.setVisibility(View.GONE);
			h.progressLayoutView.setVisibility(View.VISIBLE);

			h.progressStatus.setText(R.string.pause);
			h.progressSize.setText(getProgressString(h.downloadItem, h.apk, h.dlId));
			h.progress.setIndeterminate(false);
			h.progress.setProgress(getProgress(h.downloadItem, h.apk, h.dlId));

			h.button.setTextColor(mBlueTextColor);
			h.button.setBackgroundResource(R.drawable.download_button_blue);
			h.button.setText(R.string.go_on);
			h.button.setClickable(true);

			break;
		case DownloadService.STATUS_DOWNLOADING:
			h.info.setVisibility(View.GONE);
			h.progressLayoutView.setVisibility(View.VISIBLE);

			h.progressStatus.setText(getSpeedString(h.downloadItem));
			h.progressSize.setText(getProgressString(h.downloadItem, h.apk, h.dlId));
			h.progress.setIndeterminate(false);
			h.progress.setProgress(getProgress(h.downloadItem, h.apk, h.dlId));

			h.button.setTextColor(mGrayTextColor);
			h.button.setBackgroundResource(R.drawable.download_button_gray);
			h.button.setText(R.string.pause);
			h.button.setClickable(true);

			break;

		case DownloadService.STATUS_PREPARE_TO_DOWNLOAD:
			h.info.setVisibility(View.GONE);
			h.progressLayoutView.setVisibility(View.VISIBLE);

			h.progressStatus.setText(R.string.prepare_download);
			h.progressSize.setText(getProgressString(h.downloadItem, h.apk, h.dlId));
			h.progress.setIndeterminate(true);

			h.button.setTextColor(mGrayTextColor);
			h.button.setBackgroundResource(R.drawable.download_button_gray);
			h.button.setText(R.string.pause);
			h.button.setClickable(false);

			break;
		case DownloadService.STATUS_PREPARE_TO_STOP:
			h.info.setVisibility(View.GONE);
			h.progressLayoutView.setVisibility(View.VISIBLE);

			h.progressStatus.setText("0K/S");
			h.progressSize.setText(getProgressString(h.downloadItem, h.apk, h.dlId));
			h.progress.setIndeterminate(true);

			h.button.setTextColor(mBlueTextColor);
			h.button.setBackgroundResource(R.drawable.download_button_gray);
			h.button.setText(R.string.go_on);
			h.button.setClickable(false);

			break;
		case DownloadService.STATUS_INSTALLING:
			h.info.setVisibility(View.GONE);
			h.progressLayoutView.setVisibility(View.VISIBLE);

			h.progressStatus.setText(R.string.installing);
			h.progressSize.setText("");
			h.progress.setIndeterminate(true);

			h.button.setTextColor(mBlueTextColor);
			h.button.setBackgroundResource(R.drawable.download_button_gray);
			h.button.setText(R.string.installing);
			h.button.setClickable(false);
			break;

		case DownloadService.STATUS_PENDING:
			h.info.setVisibility(View.GONE);
			h.progressLayoutView.setVisibility(View.VISIBLE);

			h.progressStatus.setText(R.string.waiting);
			h.progressSize.setText(getSpeedString(h.downloadItem));
			h.progress.setIndeterminate(false);
			h.progress.setProgress(getProgress(h.downloadItem, h.apk, h.dlId));

			h.button.setTextColor(mGrayTextColor);
			h.button.setBackgroundResource(R.drawable.download_button_gray);
			h.button.setText(R.string.waiting);
			h.button.setClickable(true);

			break;

		case DownloadService.STATUS_DOWNLOAD_OUT_OF_DATE:
			h.info.setVisibility(View.VISIBLE);
			h.progressLayoutView.setVisibility(View.GONE);

			h.info.setText(infoText);
			h.info.setCompoundDrawablesWithIntrinsicBounds(drawableLeft, null, null, null);
			h.button.setTextColor(mBlueTextColor);
			h.button.setBackgroundResource(R.drawable.download_button_blue);
			if (PackageUtils.isPackageInstalled(mDLActivity, apk.getPackageName())) {
				h.button.setText(R.string.update);
			} else {
				h.button.setText(R.string.download);
			}
			h.button.setClickable(true);

			break;
		case DownloadService.STATUS_NEED_TO_UPDATE:
			h.info.setVisibility(View.VISIBLE);
			h.progressLayoutView.setVisibility(View.GONE);

			h.info.setText(infoText);
			h.info.setCompoundDrawablesWithIntrinsicBounds(drawableLeft, null, null, null);
			h.button.setTextColor(mBlueTextColor);
			h.button.setBackgroundResource(R.drawable.download_button_blue);
			h.button.setText(R.string.update);
			h.button.setClickable(true);
			break;
		default:
			LogUtil.w(TAG, "unknown status:" + status);
			break;
		}

		h.button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				int status = mDLActivity.getDownloadStatus(h.dlId, h.apk.getPackageName(), h.apk.getVersionCode());
				switch (status) {
				case DownloadService.STATUS_INSTALLED: {
					try {
						Intent intent = getContext().getPackageManager()
								.getLaunchIntentForPackage(h.apk.getPackageName());
						mDLActivity.startActivity(intent);
					} catch (Exception e) {
						e.printStackTrace();
						Toast.makeText(mDLActivity, "打开失败", Toast.LENGTH_SHORT).show();
					}
				}
					break;

				case DownloadService.STATUS_CAN_INSTALL: {
					mDLActivity.installApk(h.downloadItem);
				}
					break;
				case DownloadService.STATUS_DOWNLOADING: {
					mDLActivity.stopDownload(h.dlId);
				}
					break;
				case DownloadService.STATUS_NO_STATUS: {
					mDLActivity.addDownload(h.apk.getDownloadUrl().getUrl(), h.apk.getTitle(), h.apk.getPackageName(),
							h.apk.getVersionName(), h.apk.getVersionCode(), h.apk.getMd5(), h.iconUrl,
							ApkSource.toSourceString(getApkSource()));

					if (DownloadUtils.isMobileNetwork(mDLActivity)) {
						Toast.makeText(mDLActivity, R.string.download_in_gprs, Toast.LENGTH_LONG).show();
					}
				}
					break;

				case DownloadService.STATUS_PAUSED_BY_ERROR:
				case DownloadService.STATUS_PAUSED_BY_MOBILE_NETWORK:
				case DownloadService.STATUS_PAUSED_BY_USER:
					mDLActivity.startDownload(h.dlId);
					if (DownloadUtils.isMobileNetwork(mDLActivity)) {
						Toast.makeText(mDLActivity, R.string.download_in_gprs, Toast.LENGTH_LONG).show();
					}
					break;
				case DownloadService.STATUS_PENDING:
					mDLActivity.stopDownload(h.dlId);
					break;
				case DownloadService.STATUS_DOWNLOAD_OUT_OF_DATE: // 下载过期状态，强制处理为有更新状态，点击后重新开始下载
					// mDLActivity.removeDownloadImmediately(h.dlId);
					// mDLActivity.removeDownloadFiles(h.apk.getDownloadUrl().getUrl());

					mDLActivity.removeOutofDateDownloads(h.apk.getPackageName());

					mDLActivity.addDownload(h.apk.getDownloadUrl().getUrl(), h.apk.getTitle(), h.apk.getPackageName(),
							h.apk.getVersionName(), h.apk.getVersionCode(), h.apk.getMd5(), h.iconUrl,
							ApkSource.toSourceString(getApkSource()));
					if (DownloadUtils.isMobileNetwork(mDLActivity)) {
						Toast.makeText(mDLActivity, R.string.download_in_gprs, Toast.LENGTH_LONG).show();
					}
					break;
				case DownloadService.STATUS_NEED_TO_UPDATE:
					mDLActivity.addDownload(h.apk.getDownloadUrl().getUrl(), h.apk.getTitle(), h.apk.getPackageName(),
							h.apk.getVersionName(), h.apk.getVersionCode(), h.apk.getMd5(), h.iconUrl,
							ApkSource.toSourceString(getApkSource()));
					if (DownloadUtils.isMobileNetwork(mDLActivity)) {
						Toast.makeText(mDLActivity, R.string.download_in_gprs, Toast.LENGTH_LONG).show();
					}
					break;
				default:
					break;
				}
			}
		});

	}

	@Override
	public void onPackageInstalled(String pkgName) {
		if (mHolders == null) {
			return;
		}
		boolean changed = false;
		for (AppHolder h : mHolders) {
			if (pkgName.equals(h.apk.getPackageName())) {
				changed = true;
			}
		}
		if (changed) {
			refreshList(getIndex());
		}
	}

	@Override
	public void onPackageUninstalled(String pkgName) {
		if (mHolders == null) {
			return;
		}
		boolean changed = false;
		for (AppHolder h : mHolders) {
			if (pkgName.equals(h.apk.getPackageName())) {
				changed = true;
			}
		}
		if (changed) {
			refreshList(getIndex());
		}
	}

	@Override
	public void onDownloadCreated(DownloadItem di) {
		if (mHolders == null) {
			return;
		}
		boolean changed = false;
		for (AppHolder h : mHolders) {
			if (di.getId().equals(h.dlId)) {
				h.downloadItem = di;
				changed = true;
			}
		}
		if (changed) {
			refreshList(getIndex());
		}
	}

	@Override
	public void onDownloadRemoved(String id) {
		if (mHolders == null) {
			return;
		}
		boolean changed = false;
		for (AppHolder h : mHolders) {
			if (id.equals(h.dlId)) {
				h.downloadItem = null;
				changed = true;
			}
		}
		if (changed) {
			refreshList(getIndex());
		}

	}

	@Override
	public void onDownloadChanged(DownloadItem di) {
		if (mHolders == null) {
			return;
		}
		boolean changed = false;
		for (AppHolder h : mHolders) {
			if (di.getId().equals(h.dlId)) {
				h.downloadItem = di;
				changed = true;
			}
		}
		if (changed) {
			refreshList(getIndex());
		}
	}

	@Override
	public void onProgressChanged(String id, long downloaded, long speed) {
		if (mHolders == null) {
			return;
		}
		boolean changed = false;
		for (AppHolder h : mHolders) {
			if (h.downloadItem == null) {
				continue;
			}
			if (id.equals(h.dlId)) {
				h.downloadItem.setDownloadedSize(downloaded);
				h.downloadItem.setSpeed(speed);
				changed = true;
			}
		}
		if (changed) {
			refreshList(getIndex());
		}
	}

	private static class AppHolder {
		private String dlId;
		private int top;
		private Apk apk;
		private String iconUrl;
		private DownloadItem downloadItem;
		private TextView topView;
		private TextView info;
		private TextView progressStatus;
		private ProgressBar progress;
		private Button button;
		private ImageView icon;
		private TextView name;
		private TextView desc;

		private View progressLayoutView;
		private TextView progressSize;
	}

	private static class GroupApkTopHeader extends CardHeader {
		private CardGroupApkTop mCardGroupApkTop;

		public GroupApkTopHeader(Context context, CardGroupApkTop cardGroupApkTop) {
			super(context, R.layout.group_apk_top_header);
			mCardGroupApkTop = cardGroupApkTop;
		}

		@Override
		public void setupInnerViewElements(ViewGroup parent, View view) {
			if (view == null) {
				return;
			}
			TextView title = view.findViewById(R.id.group_apk_topheader_title);
			title.setText(mCardGroupApkTop.getTitle());

		}
	}

}